package com.ldy.core.common;

import java.io.File;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.config.MagicFunction;
import org.ssssssss.script.annotation.Comment;
import org.ssssssss.script.annotation.Function;

import com.github.binarywang.wxpay.service.WxPayService;
import com.ldy.core.entity.BaseUser;
import com.ldy.core.service.BaseLogsService;
import com.ldy.core.util.MySession;
import com.ldy.core.util.WechatUtil;

import cn.hutool.core.util.ZipUtil;

/**
 * 自定义函数
 */
@Component
public class MyCustomFunction implements MagicFunction {

	private static final Logger logger = LoggerFactory.getLogger(MyCustomFunction.class);

	@Autowired
	private BaseLogsService logs;

	@Autowired
	private WechatUtil wechatUtil;
	
	@Autowired
	private WxPayService wxService;

	/**
	 * 获取当前用户
	 * 
	 * @return
	 */
	@Function
	@Comment("获取当前登录对象")
	public static BaseUser user() {
		logger.info("获取当前用户信息");
		BaseUser user = MySession.get();
		logger.info("获取当前用户信息:{}", user == null);
		return user;
	}

	/**
	 * 解压文件
	 * 
	 * @return
	 */
	@Function
	@Comment("解压")
	public static String unzip(InputStream io) {
		logger.info("解压");
		ZipUtil.unzip(io, new File("/Users/lindeyi/workspace/MyProject/2023/museum-project/museum-h5/compress/src"),
				Charset.defaultCharset());

		return null;
	}

	/**
	 * 日志
	 * 
	 * @return
	 */
	@Function
	@Comment("日志")
	public boolean log(String type, String msg, String userId) {
		logger.info("日志: type: {}, msg: {}", type, msg);
		try {
			logs.insert(type, msg);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 获取微信手机号
	 * 
	 * @return
	 */
	@Function
	@Comment("获取微信手机号")
	public String getWechatPhone(String code) {
		logger.info("获取微信手机号: {}", code);
		return wechatUtil.getPhoneNumber(code);
	}

	/**
	 * 微信登录
	 * 
	 * @return
	 */
	@Function
	@Comment("微信登录")
	public String loginWechat(String code) {
		logger.info("微信登录:{}", code);
		return wechatUtil.login(code);
	}
	
	/**
	 * 微信支付接口
	 * 
	 * @return
	 */
	@Function
	@Comment("微信支付接口")
	public WxPayService getWechatPay() {
		logger.info("微信支付接口");
		return wxService;
	}

	/**
	 * 锁
	 */
	public volatile static Map<String, ReentrantLock> locks = new HashMap<>();

	

	/**
	 * 添加锁
	 * <pre>
	 * lock.lock();
	 * lock.unlock();
	 * </pre>
	 * @return
	 */
	@Function
	@Comment("添加锁")
	public ReentrantLock getLock(String username) {
		return locks.computeIfAbsent(username, k -> new ReentrantLock());
	}
}
